//
//  LocationForecastViewModel.swift
//  SwiftWeather
//
//  Created by shen on 2023/8/29.
//

import Foundation
import Combine

final class LocationForecastViewModel {
    @Published private var isLoading = true
    @Published private var isResieved = false

    var isCityInMyLocations: Bool {
        UserDefaults.standard.fetchCities()?.contains(city) ?? false
    }

    var weatherRecievedPublisher: AnyPublisher<Bool, Never> {
        $isResieved.eraseToAnyPublisher()
    }

    private let weatherRecievedSubject = PassthroughSubject<Void, Never>()

    private var cancellables = Set<AnyCancellable>()

    private let weatherService: WeatherAPIService = .shared
    private let city: City
    private var weather: Weather?

    init(city: City) {
        self.city = city
    }

    func viewModelForWeatherForecastView() -> ForecastViewViewModel {
        return ForecastViewViewModel(weather: weather)
    }

    func getWeatherForecast() {
        guard let coordinate = city.coordinate else { return }
        isLoading = true
        getForecastForLocation(with: coordinate)
    }
}

// MARK: - Private methods

private extension LocationForecastViewModel {
    func getForecastForLocation(with coordinate: Coordinate) {
        do {
            let weatherForecast = try weatherService.getForecast(coordinate: coordinate)

            weatherForecast
                .receive(on: DispatchQueue.main)
                .sink { [weak self] completion in
                    if case .failure(let error) = completion {
                        self?.isResieved = false
                        print(error)
                    }
                    self?.isLoading = false
                } receiveValue: { [weak self] weather in
                    self?.weather = weather
                    self?.isLoading = false
                    self?.isResieved = true
                }
                .store(in: &cancellables)

        } catch {
            print(error.localizedDescription)
        }
    }
}
